﻿package Server.AHMJ.HQMJ;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.json.*;
import com.mysql.cj.x.json.JsonArray;

import Server.Agent.GameDB;
import Server.Model.Base.UploadUtil;

public class Replay {
	JSONArray list = new JSONArray();
	JSONArray indexList = new JSONArray();
	Map<String, String> avatarMap = new HashMap<>();
	Map<String, String> yupaiMap = new HashMap<>();

	public void AddJsonMsg(int bySeatID, String msg) {
		JSONObject json = new JSONObject(msg);
		String[] vecs = json.optString("mjmsg").split("\\|");
		String cmd = vecs[0];
		// kehupai
		// fapai
		String oneCmds = "|joinroom|param|";
		String oneSitCmds = "|sit|mopai|chupai|chipai|pengpai|gangpai|ting";
		String noCmds = "|table_begin|table_end|table_side|leave|online|offline|try_dismissroom|cancel_dismissroom|agree_dismissroom|refuse_dismissroom|dismissroom|voicemsg|buxu_chupai|status_free|status_play|standup|kick|ready|roomuser|voice|yuyin|biaoqing|text|koupai|";

		if (oneCmds.indexOf("|" + cmd + "|") != -1) {
			if (bySeatID != 0) {
				return;
			}
		}

		if (noCmds.indexOf("|" + cmd + "|") != -1) {
			return;
		}

		if (oneSitCmds.indexOf("|" + cmd + "|") != -1) {

			int num1 = Integer.parseInt(vecs[1]);
			int num2 = Integer.parseInt(vecs[2]);
			if (num1 != bySeatID && num2 != bySeatID) {
				return;
			}
			if ("chupai".equals(cmd)) {
				if (vecs[5].indexOf("99") != -1) {
					System.out.println("无法存进reply的:" + msg +  "  id=" + bySeatID);
					return;
				}
			} else if ("mopai".equals(cmd)) {
				int num3 = Integer.parseInt(vecs[3]);
				if (num3 == 99) {
					return;
				}
			} else if ("pengpai".equals(cmd)) {
				if (vecs[7].indexOf("99") != -1) {
					return;
				}
			} else if ("gangpai".equals(cmd)) {
				if (vecs[10].indexOf("99") != -1) {
					return;
				}
			}

		}

		if ("avatar".equals(cmd)) {
			String v = vecs[1];
			if (avatarMap.containsKey(v)) {
				return;
			}
			avatarMap.put(v, v);
		}

//		if ("yupai".equals(cmd)) {
//			String v = vecs[1];
//			if (yupaiMap.containsKey(v)) {
//				return;
//			}
//			yupaiMap.put(v, v);
//		}

		addAction(new Action(bySeatID, msg));
	}

	private void addAction(Action action) {
		list.put(action.getJson());
	}

	public void SetIndexJushu(int jushu) {
		JSONObject json = new JSONObject();
		json.put(jushu + "", list.length());
		indexList.put(json);
	}

	public String save(int m_dwTableID,JSONObject toMysql) {
		if (list.length() < 10) {
			list = new JSONArray();
			indexList = new JSONArray();
			return "no";
		}
		SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
		String today = df1.format(new Date());

		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMdd_HHmmss");

		String replay_id = String.format("hqmj.%s_%d", df2.format(new Date()), m_dwTableID);

		SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String created = df3.format(new Date());

		String filePath = "./replay/" + today + "/" + replay_id + ".json";
		String relativePath = "replay/" + today + "/" + replay_id + ".json";
		toMysql.put("battle_video",relativePath);

		File file = new File(filePath);
		File parent = file.getParentFile();
		if (parent != null && !parent.exists()) {
			parent.mkdirs();
		}

		try {
			OutputStream out = new FileOutputStream(file);
			BufferedWriter rd = new BufferedWriter(new OutputStreamWriter(out, "utf-8"));
			JSONObject json = new JSONObject();
			json.put("data", list);
			json.put("dataIndex", indexList);
			rd.write(json.toString());

			rd.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Map<String, String> params = new HashMap<String, String>();
		ReplayRecorder.getInstance().pushReply(toMysql, filePath, params);
		indexList = new JSONArray();
		list = new JSONArray();
		return null;
	}
}

class Action {
	public JSONObject getJson() {
		JSONObject json = new JSONObject();
		json.put("bySeatID", bySeatID);
		json.put("msg", msg);
		return json;
	}

	int bySeatID;
	String msg;

	Action(int sit, String msg) {
		this.bySeatID = sit;
		this.msg = msg;
	}
}

class ReplayRecorder {
	class ReplyObj{
		public String _filePath;
		public org.json.JSONObject _toMysql;
		public Map<String, String> _params;
	}
	private static ReplayRecorder _instance = null;
	public static ReplayRecorder getInstance(){
		if(_instance == null){
			_instance = new ReplayRecorder();
			_instance.startReplaySaveTask();
		}
		return _instance;
	}
	class ReplayTaskThread implements Runnable {
		public UploadUtil uploadUtil = UploadUtil.getInstance();
		public boolean _isRunning = true;
		public GameDB _db = GameDB.getInstance();
        public void run() {
        	synchronized(_saveThread)
        	{
	            while (true) {
	            	ReplyObj msg = _msgQueue.poll();
	                if (msg == null) {
	                	try {
	                		_saveThread._isRunning = false;
	                		_saveThread.wait();
	                		_saveThread._isRunning = true;
						} catch (InterruptedException e) {
							
						}
	                }else{
	            		String rev = uploadUtil.uploadFile(msg._filePath, "file", "http://uploadreplay.qilehuyu.cn/uploadreplay.php", msg._params,
	            				"application/octet-stream");
	                	/*
	            		String rev = uploadUtil.uploadFile(msg._filePath, "file", "http://test3.com:89/zy_server/php-web/upload/uploadReply.php", msg._params,
	            				"application/octet-stream");
	            				*/
	            		if(rev != null){
	            			//upload success,save record to mysql
	            			_db.push_task(null,msg._toMysql);
		                	msg = null;
	            		}else{
	            			//upload failed,do nothing
//	            			if(_msgQueue.size() < 1000){
//	            				_msgQueue.add(msg);
//	            			}
	            		}
	                }
	            }
        	}
        }
    }
	private ConcurrentLinkedQueue<ReplyObj> _msgQueue = new ConcurrentLinkedQueue<ReplyObj>();
	ReplayTaskThread _saveThread = new ReplayTaskThread();
	public void pushReply(JSONObject toMysql,String filePath,Map<String, String> params){
		boolean empty = _msgQueue.isEmpty();
		ReplyObj obj = new ReplyObj();
		obj._toMysql = toMysql;
		obj._filePath = filePath;
		obj._params = params;
		_msgQueue.add(obj);
		if(empty){
			synchronized(_saveThread){
				if(_saveThread._isRunning == false){
					_saveThread.notify();
				}
			}
		}
	}
	private void startReplaySaveTask(){
		new Thread(_saveThread).start();
	}
}
